package com.wzt.lianfirecontrol.fragment.yinghuan;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.ShowFragActivity;
import com.wzt.lianfirecontrol.adapter.yighuan.YingHuanRecordAdapter;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.function.yinhuan.YingHuanModel;
import com.wzt.lianfirecontrol.bean.recode.function.yinhuan.YingHuanRecordModel;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.GildeUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.ScreenUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class YingHuanDetailFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener, YingHuanRecordAdapter.CallBack {
    private BaseActivity activity;
    private Bundle bundle;
    private View itemContentView;

    private SuperSwipeRefreshLayout swipeRefreshLayout;

    private RecyclerView rlv_list;
    private LinearLayoutManager linearLayoutManager;
    private YingHuanRecordAdapter yingHuanRecordAdapter;

    private LinearLayout ll_title;
    private TextView tv_title;
    private TextView tv_status;
    private TextView tv_device_location;
    private TextView tv_person_name;
    private TextView tv_person_phone;
    private LinearLayout ll_handle_time;
    private TextView tv_handle_time;
    private View v_handle_line;
    private TextView tv_error_time;
    private TextView tv_error_content;

    private LinearLayout ll_device_three_photo;
    private View include_play_photo_three;
    private RelativeLayout rl_device_photo_1;
    private ImageView iv_device_photo_1;
    private ImageView iv_photo_delete_1;
    private RelativeLayout rl_device_photo_2;
    private ImageView iv_device_photo_2;
    private ImageView iv_photo_delete_2;
    private RelativeLayout rl_device_photo_3;
    private ImageView iv_device_photo_3;
    private ImageView iv_photo_delete_3;

    private LinearLayout ll_record_title;

    private TextView tv_add_record;

    private View include_no_data;
    private View include_no_net;
    private View include_progress_bar;

    private static final int RECORD_WHAT = 0;

    private YingHuanModel yingHuanModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            activity = getMyActivity();
            bundle = getArguments();
            if (null != bundle){
                yingHuanModel = (YingHuanModel) bundle.getSerializable("data");
            }
            if (null == yingHuanModel){
                activity.finish();
            }
            PreferencesUtils.putString(activity, ConstData.CHANGESTATUS, "-1");
            itemContentView = inflater.inflate(R.layout.f_yinghuan_detail, container, false);
            initView();
            setDetailData();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        swipeRefreshLayout = itemContentView.findViewById(R.id.swipe_container);
        InitView.instance().initSuperSwipeLayout(swipeRefreshLayout);
        swipeRefreshLayout.setOnSwipeRefreshListener(this);

        rlv_list = itemContentView.findViewById(R.id.rlv_list);
        linearLayoutManager = new LinearLayoutManager(activity);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        rlv_list.setLayoutManager(linearLayoutManager);
        yingHuanRecordAdapter = new YingHuanRecordAdapter(activity, this);
        rlv_list.setAdapter(yingHuanRecordAdapter);

        initHeadView();

        tv_add_record = itemContentView.findViewById(R.id.tv_add_record);

        include_no_data = itemContentView.findViewById(R.id.include_no_data);
        include_progress_bar = itemContentView.findViewById(R.id.include_progress_bar);
        InitView.instance().initProgressBar(activity, include_progress_bar);
        include_no_net = itemContentView.findViewById(R.id.include_no_net);
        include_no_net.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateData();
            }
        });
    }

    private void initHeadView() {
        View headView = LayoutInflater.from(activity).inflate(R.layout.head_yinghuan_detail, rlv_list, false);
        ll_title = headView.findViewById(R.id.ll_title);
        tv_title = headView.findViewById(R.id.tv_title);
        tv_status = headView.findViewById(R.id.tv_status);
        tv_device_location = headView.findViewById(R.id.tv_device_location);
        tv_person_name = headView.findViewById(R.id.tv_person_name);
        tv_person_phone = headView.findViewById(R.id.tv_person_phone);
        ll_handle_time = headView.findViewById(R.id.ll_handle_time);
        tv_handle_time = headView.findViewById(R.id.tv_handle_time);
        v_handle_line = headView.findViewById(R.id.v_handle_line);
        ll_handle_time.setVisibility(View.GONE);
        v_handle_line.setVisibility(View.GONE);
        tv_error_time = headView.findViewById(R.id.tv_error_time);
        tv_error_content = headView.findViewById(R.id.tv_error_content);

        initPhotoThree(headView);

        ll_record_title = headView.findViewById(R.id.ll_record_title);

        yingHuanRecordAdapter.setHeaderView(headView);
    }

    private void initPhotoThree(View headView) {
        ll_device_three_photo = headView.findViewById(R.id.ll_device_three_photo);
        include_play_photo_three = headView.findViewById(R.id.include_play_photo_three);
        rl_device_photo_1 = headView.findViewById(R.id.rl_device_photo_1);
        iv_device_photo_1 = headView.findViewById(R.id.iv_device_photo_1);
        iv_photo_delete_1 = headView.findViewById(R.id.iv_photo_delete_1);
        iv_photo_delete_1.setVisibility(View.GONE);
        rl_device_photo_2 = headView.findViewById(R.id.rl_device_photo_2);
        iv_device_photo_2 = headView.findViewById(R.id.iv_device_photo_2);
        iv_photo_delete_2 = headView.findViewById(R.id.iv_photo_delete_2);
        iv_photo_delete_2.setVisibility(View.GONE);
        rl_device_photo_3 = headView.findViewById(R.id.rl_device_photo_3);
        iv_device_photo_3 = headView.findViewById(R.id.iv_device_photo_3);
        iv_photo_delete_3 = headView.findViewById(R.id.iv_photo_delete_3);
        iv_photo_delete_3.setVisibility(View.GONE);

        int width = (ScreenUtils.getScreenWidth(activity) - Utils.dip2px(activity, 90)) / 3;
        rl_device_photo_1.getLayoutParams().width = width;
        rl_device_photo_1.getLayoutParams().height = width;
        rl_device_photo_2.getLayoutParams().width = width;
        rl_device_photo_2.getLayoutParams().height = width;
        rl_device_photo_3.getLayoutParams().width = width;
        rl_device_photo_3.getLayoutParams().height = width;

    }

    private void initDetailRecordHttpHelper() {
        try {
            if (Utils.hasNetwork(activity)){
                include_no_net.setVisibility(View.GONE);
            }else {
                include_no_net.setVisibility(View.VISIBLE);
                return;
            }
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", yingHuanModel.getId());

            HashMap<String, String> url_params = new HashMap<>();
            url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
            DetailHttpHelper detailHttpHelper = new DetailHttpHelper(activity, Url.YIHUAN_RECORD_LIST_URL, RECORD_WHAT, handler, true, url_params);
            detailHttpHelper.setParseJsonData(new LoginParseJsonData());
            detailHttpHelper.getHttpRequest(true);
        }catch (Exception e){}
    }

    @Override
    public void onSwipeRefresh() {
        swipeRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
                updateData();
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {

    }

    @Override
    public void onPullEnableMoreAction(boolean enable) {

    }

    @Override
    public void showImage(String imgUrl) {
        ((ShowFragActivity)activity).setShowImg(imgUrl);
    }

    class DetailHttpHelper extends HttpHelper {

        public DetailHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class LoginParseJsonData extends ParseJsonData {

        public LoginParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            switch (what){
                case RECORD_WHAT:
                    try {
                        LinkedList<YingHuanRecordModel> yingHuanRecordModels = (LinkedList<YingHuanRecordModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr), YingHuanRecordModel.class);
                        bundle.putSerializable("yuyueRecordModels", yingHuanRecordModels);
                        bundle.putBoolean(REQUEST_OK, true);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        bundle.putBoolean(REQUEST_OK, false);
                        bundle.putString(ERROR_MSG, ANALYZE_ERROR_MSG);
                    }
                    break;
            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){
            include_progress_bar.setVisibility(View.GONE);
            return;
        }
        switch (msg.what){
            case RECORD_WHAT:
                include_progress_bar.setVisibility(View.GONE);
                setRecordListData((LinkedList<YingHuanRecordModel>)bundle.getSerializable("yuyueRecordModels"));
                break;
        }
    }

    private void setDetailData() {
        if (null == yingHuanModel){
            include_no_data.setVisibility(View.VISIBLE);
            return;
        }
        include_no_data.setVisibility(View.GONE);
        StringBuilder stringBuilder = new StringBuilder();
        if (!StringUtils.isEmpty(yingHuanModel.getBuildingName())){
            stringBuilder.append(yingHuanModel.getBuildingName());
        }
        if (!StringUtils.isEmpty(yingHuanModel.getFloorName())){
            stringBuilder.append(yingHuanModel.getFloorName());
        }
        if (!StringUtils.isEmpty(yingHuanModel.getAddress())){
            stringBuilder.append(yingHuanModel.getAddress());
        }
        if (StringUtils.isEmpty(stringBuilder.toString())){
            tv_device_location.setVisibility(View.GONE);
        }else {
            tv_device_location.setText(stringBuilder.toString());
        }
        tv_person_name.setText(yingHuanModel.getRealName());
        tv_person_phone.setText(yingHuanModel.getPhone());
        tv_error_time.setText(yingHuanModel.getOccurTimeStr());
        tv_error_content.setText(yingHuanModel.getRemark());

        String[] imgUrls = yingHuanModel.getImgUrls().split(",");
        if (imgUrls.length >= 1 && imgUrls[0].startsWith("http")){
            GildeUtils.loadImageCorner(activity, iv_device_photo_1, imgUrls[0]);
            iv_device_photo_1.setVisibility(View.VISIBLE);
            iv_device_photo_1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ShowFragActivity)activity).setShowImg(imgUrls[0]);
                }
            });
        }else {
            iv_device_photo_1.setVisibility(View.GONE);
        }

        if (imgUrls.length >= 2){
            GildeUtils.loadImageCorner(activity, iv_device_photo_2, imgUrls[1]);
            iv_device_photo_2.setVisibility(View.VISIBLE);
            iv_device_photo_2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ShowFragActivity)activity).setShowImg(imgUrls[1]);
                }
            });
        }else {
            iv_device_photo_2.setVisibility(View.GONE);
        }

        if (imgUrls.length >= 3){
            GildeUtils.loadImageCorner(activity, iv_device_photo_3, imgUrls[2]);
            iv_device_photo_3.setVisibility(View.VISIBLE);
            iv_device_photo_3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((ShowFragActivity)activity).setShowImg(imgUrls[2]);
                }
            });
        }else {
            iv_device_photo_3.setVisibility(View.GONE);
        }

        if (StringUtils.isEmpty(yingHuanModel.getName())){
            tv_title.setVisibility(View.INVISIBLE);
        }else {
            tv_title.setVisibility(View.VISIBLE);
            tv_title.setText(yingHuanModel.getName());
        }


        List<String> alias = UserInfoModel.getUserInfo(getActivity()).getRoleAlias();
        // 维保人员和维保管理人员只显示预约维保单
        // 组织管理员 ROLE_ORG_MANAGER  先判断是否是组织管理员，是，就只能看，不能操作。不是的话，判断是否是维保人员


        if ("0".equals(yingHuanModel.getStatus())){
            tv_status.setText("待整改");
            tv_status.setTextColor(activity.getResources().getColor(R.color.change_status_color));
           // tv_add_record.setVisibility(View.VISIBLE);
            if (alias.contains(RoleConstant.ROLE_ORG_MANAGER)) {

                tv_add_record.setVisibility(View.GONE);

            }else {

                tv_add_record.setVisibility(View.VISIBLE);

            }
            ll_handle_time.setVisibility(View.GONE);
            v_handle_line.setVisibility(View.GONE);
        }else if ("2".equals(yingHuanModel.getStatus())){
            tv_status.setText("已整改");
            tv_status.setTextColor(activity.getResources().getColor(R.color.look_status_color));
            tv_add_record.setVisibility(View.GONE);
   /*         if (alias.contains(RoleConstant.ROLE_ORG_MANAGER)) {

                tv_add_record.setVisibility(View.GONE);

            }else {

                tv_add_record.setVisibility(View.VISIBLE);

            }*/
            // 已整改需要显示解决时间
            if (StringUtils.isEmpty(yingHuanModel.getHandingTimeStr())) {
                ll_handle_time.setVisibility(View.GONE);
                v_handle_line.setVisibility(View.GONE);
            }else {
                ll_handle_time.setVisibility(View.VISIBLE);
                v_handle_line.setVisibility(View.VISIBLE);
                tv_handle_time.setText(yingHuanModel.getHandingTimeStr());
            }
        }else {
            tv_status.setText("整改中");
            tv_status.setTextColor(activity.getResources().getColor(R.color.remark_status_color));
           // tv_add_record.setVisibility(View.VISIBLE);
            if (alias.contains(RoleConstant.ROLE_ORG_MANAGER)) {

                tv_add_record.setVisibility(View.GONE);

            }else {

                tv_add_record.setVisibility(View.VISIBLE);

            }
            ll_handle_time.setVisibility(View.GONE);
            v_handle_line.setVisibility(View.GONE);
        }

        tv_add_record.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!UserInfoModel.isSelfCompany(activity)){
            //        ToastUtils.showToast(activity, ConstData.ERROR_COMPANY_MSG);
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("riskId", yingHuanModel.getId());
                activity.setClickAction(ConstData.SHOWFRAG, ConstData.ADDYINGHUANRECORD, "添加整改记录", null, bundle);
            }
        });

    }

    private void setRecordListData(LinkedList<YingHuanRecordModel> yingHuanRecordModels) {
        yingHuanRecordAdapter.clear();
        if (null != yingHuanRecordModels && yingHuanRecordModels.size() > 0){
            ll_record_title.setVisibility(View.VISIBLE);
            yingHuanRecordAdapter.addDatas(yingHuanRecordModels);
        }else {
            ll_record_title.setVisibility(View.GONE);
        }
    }

    @Override
    public void updateData() {
        super.updateData();
        initDetailRecordHttpHelper();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateData();
        if (null != yingHuanModel) {
            if ("0".equals(PreferencesUtils.getString(activity, ConstData.CHANGESTATUS, "-1"))) {
                // 待整改
                yingHuanModel.setStatus("1");
                setDetailData();
            } else if ("1".equals(PreferencesUtils.getString(activity, ConstData.CHANGESTATUS, "-1"))) {
                // 已整改
                yingHuanModel.setStatus("2");
                setDetailData();
            }
            PreferencesUtils.putString(activity, ConstData.CHANGESTATUS, "-1");

        }

    }
}
